$(function(){
	$('.tabs').tabs({
		beforeLoad: function(e, ui) {
			ui.jqXHR.error(function(req){
				ui.panel.html(req.status + '. ' + req.statusText);
			});
		},
		create: function(e, ui) {
			var indx = $(this).tabs('option', 'active');
			cookieSet('price-tab-index', indx);
		},
		activate: function(e, ui) {
			var indx = $(this).tabs('option', 'active');
			cookieSet('price-tab-index', indx);
		},
		active: cookieGet('price-tab-index')
	});
	
	initGroupForm($('#add-price-group'));
});

function initGroupForm(span) {
	
	span.find('input').keyup(function(e){
		switch(e.keyCode) {
		case 13:
			$(this).siblings('.save').click()
			break;
		case 27:
			$(this).siblings('.cancel').click()
			break;
		}
	});
	
	span.find('.cancel').click(function(){
		$('#add-price-group').hide();
		$('#add-price-group-btn').show();
	});
	
	span.find('.save').click(function(){
		var inpt = $(this).siblings('input');
		var groupId = $(this).parent().data('group-id');
		var newName = inpt.val();
		
		if (! newName.length) {
			return $(this).siblings('.cancel').click();
		}
		
		PUT('/admin_cene/save_group', {
			PriceGroup: {id: groupId, name: newName}
		}, function(req){
			hideThrobber();
			
			if (req.status == 200) {
				location.reload();
			} else {
				flash(req.getResponseHeader('errorMessage'));
			}
		});
	});
}

function addPriceGroup() {
	var tpl = $('#add-price-group');
	var btn = $('#add-price-group-btn');
	
	btn.hide();
	tpl.show();
	tpl.find('input').focus();
}

function priceGroupDeleted(id) {
	$('#price-group-li-' + id).remove();
	
	var tabs = $('#price-tabs');
	if (tabs.children('ul').children('li').length) {
		tabs.show().tabs('option', 'active', 0);
	} else {
		tabs.hide();
	}
}

function savePrices(form) {
	var form = $(form);
	PUT(form.attr('action'), form.serialize(), function(req){
		hideThrobber();
		
		if (req.status == 200) {
			location.reload()
		} else {
			flash(req.getResponseHeader('errorMessage'))
		}
	});
}